﻿Public Class frm_CSModeDefine
    Implements IDServer.IDServer.IDServer


    Private ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

    Public WithEvents MainFrom As Frm_MainForm
    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainFrom
        End Get
        Set(ByVal value As Frm_MainForm)
            MainFrom = value
        End Set
    End Property

    Private dtCsTypes As DataTable

#Region " Interface Methods "

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        If AddEnable = False Then
            MessageBox.Show("對不起，您沒有新增權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If
        Dim node As TreeNode = Me.tv.SelectedNode
        If Not node Is Nothing AndAlso node.Level < 3 Then
            ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd
            If node.Name <> "0" Then
                ClearText(True)
                Me.tbxfParentCode.Text = node.Name
                Me.tbxfName.Focus()
                SetButton(ButtonType.Add, True)
            Else
                ClearText(True)
                Me.tbxfName.Focus()
                Me.tbxfParentCode.Text = node.Name
                SetButton(ButtonType.Add, True)
            End If
            Me.tv.Enabled = False
        Else
            Me.MainFrom.ToolStripCancel.Enabled = True
            Me.MainFrom.ToolStripCancel.PerformClick()
        End If
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        Try
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            Dim isFind As Boolean = False
            If Not Me.tv.SelectedNode Is Nothing AndAlso Me.tv.SelectedNode.Level > 0 Then
                isFind = True
            End If
            Me.SetButton(ButtonType.Browse, isFind)
            Dim node As TreeNode = Me.tv.SelectedNode
            Me.tv.Enabled = True
            If Not node Is Nothing Then
                Me.tv.Select()
                Me.tv_AfterSelect(Me.tv, New TreeViewEventArgs(node))
            End If
        Catch ex As Exception
            MsgBox("ActionCancel：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete
        If DeleteEnable = False Then
            MessageBox.Show("對不起，您沒有刪除權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If
        Dim node As TreeNode = Me.tv.SelectedNode
        If Not node Is Nothing Then
            If Msg.MsgYesNo("是否要刪除節點：" + node.Text + "  " + node.Name) = DialogResult.Yes Then
                Dim rows() As DataRow = Me.dtCsTypes.Select("fCode='" + node.Name + "'")
                If rows.Length > 0 Then
                    Dim sql As String = "delete from CS_CusterServiceTypes where fCode='" + node.Name + "'"
                    Exec(Sql, E_ExecType.ExecuteNonQuery)
                    Me.dtCsTypes.Rows.Remove(rows(0))
                    Me.dtCsTypes.AcceptChanges()
                    Me.tv.Nodes.Remove(node)
                End If
            End If
        End If
    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        Try
            If EditEnable = False Then
                MessageBox.Show("對不起，您沒有修改權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If
            ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
            Me.SetButton(ButtonType.Edit, False)
            prepareText(True)
        Catch ex As Exception
            MsgBox("ActionEdit：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    ''' <summary>
    ''' 保存新增或修改的節點（同時更新fFullCode的值）
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        Dim node As TreeNode = Me.tv.SelectedNode
        If node Is Nothing Then
            Exit Function
        End If
        Dim newNode As TreeNode

        Dim SqlConn As New SqlClient.SqlConnection(ConnectionString)
        SqlConn.Open()
        Dim Sqlcmd As SqlClient.SqlCommand = SqlConn.CreateCommand
        Dim SqlTran As SqlClient.SqlTransaction = Nothing
        Dim sql As String = String.Empty

        Try
            Dim row As DataRow

            SqlTran = SqlConn.BeginTransaction
            Sqlcmd.Connection = SqlConn
            Sqlcmd.Transaction = SqlTran

            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                row = Me.dtCsTypes.NewRow()
                For Each col As Control In Me.GroupBox1.Controls
                    If TypeOf col Is TextBox Then
                        If Me.dtCsTypes.Columns(col.Name.Substring(3)).DataType Is GetType(Int32) Then
                        Else
                            row(col.Name.Substring(3)) = col.Text.Trim
                        End If

                    ElseIf TypeOf col Is CheckBox Then
                        row("ifRequiedChild") = CType(col, CheckBox).Checked
                    End If
                Next

                row("fParentCode") = node.Name
                row("fCode") = getNewfCode(node)
                row("fLevel") = (node.Level).ToString
                row("fType") = Convert.ToInt32(row("fCode").ToString.Substring(0, 3))
                sql = "insert into CS_CusterServiceTypes "
                Dim cols As String = ""
                Dim colsValues As String = ""
                Dim i As Int32 = dtCsTypes.Columns.Count
                For Each col As DataColumn In dtCsTypes.Columns
                    If i > 0 Then
                        If Not "|ffullcode|".Contains(col.ColumnName.ToLower) Then
                            cols = cols + IIf(i > 1, col.ColumnName + ",", col.ColumnName).ToString
                            Dim colvalue As String = IIf(TypeOf row(col.ColumnName) Is DBNull, "", row(col.ColumnName).ToString).ToString
                            colsValues = colsValues + IIf(i > 1, "N'" + colvalue + "',", "N'" + colvalue + "'").ToString
                        End If
                        i = i - 1
                    End If
                Next
                sql = sql + "(" + cols + ") values(" + colsValues + ")" + vbNewLine

                sql += "update CS_CusterServiceTypes  set fFullCode= [dbo].[GetFullPath_CSTypes]('" + row("fCode").ToString + "') where fCode='" + row("fCode").ToString + "'" + vbNewLine

                With Sqlcmd
                    .CommandType = CommandType.Text
                    .CommandText = sql
                    .ExecuteNonQuery()
                End With
                Me.dtCsTypes.Rows.Add(row)
                Me.dtCsTypes.AcceptChanges()
                newNode = New TreeNode
                newNode.Name = row("fCode").ToString
                newNode.Text = row("fName").ToString
                node.Nodes.Add(newNode)
            ElseIf ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Dim rows() As DataRow = Me.dtCsTypes.Select("fCode='" + node.Name + "'")
                If rows.Length = 0 Then
                    Exit Function
                End If
                row = rows(0)
                For Each col As Control In Me.GroupBox1.Controls
                    If TypeOf col Is TextBox Then
                        If Me.dtCsTypes.Columns(col.Name.Substring(3)).DataType Is GetType(Int32) Then
                        Else
                            row(col.Name.Substring(3)) = col.Text.Trim
                        End If

                    ElseIf TypeOf col Is CheckBox Then
                        row("ifRequiedChild") = CType(col, CheckBox).Checked
                    End If
                Next
                row("fLevel") = (node.Level - 1).ToString
                row("fType") = Convert.ToInt32(row("fCode").ToString.Substring(0, 3))
                node.Text = row("fName").ToString
                sql = "update CS_CusterServiceTypes set  "
                Dim where As String = ""
                Dim cols As String = ""
                Dim i As Int32 = dtCsTypes.Columns.Count
                For Each col As DataColumn In dtCsTypes.Columns
                    If i > 0 Then
                        If Not "|ffullcode|".Contains(col.ColumnName.ToLower) Then
                            Dim colvalue As String = IIf(TypeOf row(col.ColumnName) Is DBNull, "", row(col.ColumnName).ToString).ToString
                            If col.ColumnName.Equals("fCode", StringComparison.InvariantCultureIgnoreCase) Then
                                where = " where " + col.ColumnName + "= '" + colvalue + "'"
                            Else
                                cols = cols + IIf(i > 1, col.ColumnName + "=N'" + colvalue + "',", col.ColumnName + "=N'" + colvalue + "'").ToString
                            End If
                        End If
                        i = i - 1
                    End If
                Next
                cols = cols + ",fFullCode= [dbo].[GetFullPath_CSTypes]('" + row("fCode").ToString + "')"
                sql = sql + vbNewLine + cols + vbNewLine + where
                With Sqlcmd
                    .CommandType = CommandType.Text
                    .CommandText = sql
                    .ExecuteNonQuery()
                End With
                Me.dtCsTypes.AcceptChanges()
                newNode = node
            End If
            SqlTran.Commit()
            MsgBox(IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd, My.Resources.AddSuccess, My.resources.EditSuccess), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            Me.SetButton(ButtonType.Browse, True)
            '設置 新增或修改的節點 為當前選中節點
            If Not newNode Is Nothing Then Me.selectTreeNode(newNode)
            Return True
        Catch ex As Exception
            SqlTran.Rollback()
            MsgBox("ActionSave:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function
#End Region

#Region " User Methods "

    Private Sub selectTreeNode(ByVal node As TreeNode)
        Me.tv.Enabled = True
        If Not node Is Nothing Then
            Me.tv.Select()
            Me.tv_AfterSelect(Me.tv, New TreeViewEventArgs(node))
        End If
    End Sub

    Private Sub prepareTreeView()
        Dim sql As String = "select * from CS_CusterServiceTypes"
        dtCsTypes = Exec(sql, E_ExecType.DataTable)
        Dim node As New TreeNode
        node.Name = "0"
        node.Text = "全部"
        Me.tv.Nodes.Add(node)
        FillNode(node)
        node.Expand()
        For Each node1 As TreeNode In node.Nodes
            node1.Expand()
        Next
        Me.tv.Select()
        Me.tv.SelectedNode = node
    End Sub

    Private Sub FillNode(ByVal node As TreeNode)
        Dim rows() As DataRow = dtCsTypes.Select("fparentCode='" + node.Name + "'")
        For Each row As DataRow In rows
            Dim node1 As New TreeNode
            node1.Name = row("fCode").ToString()
            node1.Text = row("fName").ToString()
            node.Nodes.Add(node1)
            FillNode(node1)
        Next
    End Sub

    ''' <summary>
    ''' 選中一個節點后，填充該節點的內容到控件中
    ''' </summary>
    ''' <param name="node"></param>
    ''' <remarks></remarks>
    Private Sub FillControlValue(ByVal node As TreeNode, ByVal setEnable As Boolean)
        Dim rows() As DataRow = Me.dtCsTypes.Select("fCode='" + node.Name + "'")
        If rows.Length > 0 Then
            For Each col As Control In Me.GroupBox1.Controls
                If TypeOf col Is TextBox Then
                    col.Text = rows(0)(col.Name.Substring(3)).ToString
                End If
            Next
            Dim ifRequitChild As Boolean = False
            If node.Nodes.Count > 0 Then
                ifRequitChild = True
                If rows(0)("ifRequiedChild") Is Nothing OrElse rows(0)("ifRequiedChild").ToString.Equals("0") OrElse rows(0)("ifRequiedChild").ToString.ToLower.Equals("false") Then
                    ifRequitChild = False
                End If
            End If
            prepareText(setEnable)
            Me.CheckBox1.Checked = ifRequitChild
            Me.CheckBox1.Enabled = setEnable
        Else
            ClearText(setEnable)
        End If
    End Sub

    Private Sub ClearText(Optional ByVal setEnable As Boolean = False)
        For Each col As Control In Me.GroupBox1.Controls
            If TypeOf col Is TextBox Then
                col.Text = ""
                If col.Name.EndsWith("Code", StringComparison.InvariantCultureIgnoreCase) Then
                    col.Enabled = False
                ElseIf "|ftype|flevel|".Contains(col.Name.ToLower.Replace("tbx", "")) Then
                    col.Enabled = False
                Else
                    col.Enabled = setEnable
                End If
            End If
        Next
        Me.CheckBox1.Checked = False
        Me.CheckBox1.Enabled = setEnable
    End Sub

    Private Sub prepareText(Optional ByVal setEnable As Boolean = False)
        For Each col As Control In Me.GroupBox1.Controls
            If TypeOf col Is TextBox Then
                If col.Name.EndsWith("Code", StringComparison.InvariantCultureIgnoreCase) Then
                    col.Enabled = False
                ElseIf "|ftype|flevel|".Contains(col.Name.ToLower.Replace("tbx", "")) Then
                    col.Enabled = False
                Else
                    col.Enabled = setEnable
                End If
            End If
        Next
        Me.CheckBox1.Checked = False
        Me.CheckBox1.Enabled = setEnable
    End Sub

    ''' <summary>
    ''' 設置按鈕狀態
    ''' </summary>
    ''' <param name="type"></param>
    ''' <remarks></remarks>
    Private Sub SetButton(ByVal type As ButtonType, ByVal IsFind As Boolean)
        Try
            Select Case type
                Case ButtonType.Add
                    With MainFrom
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True
                        .ToolStripFind.Enabled = False
                    End With

                Case ButtonType.Browse
                    With MainFrom
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True
                        .ToolStripCheck.Enabled = False
                        .ToolStripUnCheck.Enabled = False
                        .ToolStripComplete.Enabled = False
                        .ToolStripFind.Enabled = IsFind
                    End With

                Case ButtonType.Cancel
                    With MainFrom
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind
                        .ToolStripDelete.Enabled = IsFind
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True
                        .ToolStripFind.Enabled = IsFind
                    End With

                Case ButtonType.Edit
                    With MainFrom
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True
                        .ToolStripFind.Enabled = False
                    End With

            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 根據傳入的父節點，生成新的子結點的編號。
    ''' </summary>
    ''' <param name="node">父節點</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function getNewfCode(ByVal node As TreeNode) As String
        Dim rows() As DataRow = Me.dtCsTypes.Select("fParentCode='" + node.Name + "'")
        If rows.Length > 0 Then
            Dim maxNum As Int32 = 1
            Dim num As Int32 = 0
            For Each row As DataRow In rows
                num = Convert.ToInt32(row("fCode").ToString.Substring(row("fCode").ToString.Length - 3))
                maxNum = Convert.ToInt32(IIf(maxNum > num, maxNum, num))
            Next
            Return IIf(node.Name.Equals("0"), "", node.Name).ToString + (maxNum + 1).ToString.PadLeft(3, "0")
        Else
            Return node.Name + "001"
        End If
    End Function

#End Region

#Region " Form Events "
    Private Sub frm_CSModeDefine_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each frm As Form In Application.OpenForms
            If TypeOf frm Is Frm_MainForm Then
                Me.SelectObject = frm
            End If
        Next
        prepareTreeView()
    End Sub
#End Region

#Region " Controls Events "
    Private Sub tv_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tv.AfterSelect
        Dim node As TreeNode
        If e.Action = TreeViewAction.Unknown Then
            If Me.tv.SelectedNode Is Nothing OrElse (Not Me.tv.SelectedNode Is Nothing AndAlso Not Me.tv.SelectedNode.Equals(e.Node)) Then
                Me.tv.SelectedNode = e.Node
            End If
        End If
        node = Me.tv.SelectedNode
        If Not node Is Nothing AndAlso node.Name <> "0" Then
            FillControlValue(node, IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit, True, False))
            Me.MainFrom.ToolStripEdit.Enabled = True
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
                If node.Nodes.Count = 0 Then
                    Me.MainFrom.ToolStripDelete.Enabled = True
                Else
                    Me.MainFrom.ToolStripDelete.Enabled = False
                End If
            End If
        Else
            'prepareText(False)
            ClearText(False)
            Me.MainFrom.ToolStripEdit.Enabled = False
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.ToolTip1.Show(Me.tbxfTypeCodes.Tag, Me.tbxfTypeCodes, 2000)
    End Sub

#End Region

End Class
